const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async(ctx) => {
    let room_id = ctx.request.body.room_id || '';
    let product_id = ctx.request.body.product_id || 0;
    let name = ctx.request.body.name || '';
    if (room_id <= 0 || product_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let existRows = await mysql.query(`SELECT * FROM room WHERE room_id = ?`, room_id);
        if (existRows.length <= 0){
            ctx.body = {
                result: 204,
                message: "找不到对应房间"
            };
            return
        }
        existRows = await mysql.query(`SELECT * FROM product WHERE product_id = ?`, product_id);
        if (existRows.length <= 0){
            ctx.body = {
                result: 204,
                message: "找不到对应设备"
            };
            return
        }
        let tag = "";
        if (existRows[0].control_type === 1){
            let existPropertys = await mysql.query(`SELECT property_name FROM product_property WHERE product_id = ? and parent_property_id is NULL ORDER BY property_id `, product_id);
            if (existPropertys.length > 0){
                for (let property of Object.values(existPropertys)) {
                    property.link = '';
                }
                tag = JSON.stringify(existPropertys);
                tag = tag.replace(/\"/g,'\'');
            }
        }

        let newRoomDevcieTemp = {
            room_id,
            product_id,
            name,
            tag
        };
        ret = await mysql.query(`INSERT INTO t_room_v_device SET ?`, newRoomDevcieTemp);
        if (!ret || ret.insertId === -1){
            ctx.body = {
                result: 202,
                message: "新增房间设备模板失败"
            };
        } else {
            ctx.body = {
                result: 200,
                id: ret.insertId,
                message: "新增房间设备模板成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let v_device_id = ctx.params.device_templet_id || 0;
    if (v_device_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        ret = await mysql.query(`delete from t_room_v_device WHERE v_device_id = ?`, v_device_id);
        if (!ret || ret.affectedRows === 0){
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 203,
            message: "删除失败"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let v_device_id = ctx.request.body.device_templet_id || 0;
    let name = ctx.request.body.name || '';
    let tag = (ctx.request.body.tag ? ctx.request.body.tag.trim() : '')|| '';
    if (v_device_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let selectRows = await mysql.query(`SELECT * FROM t_room_v_device WHERE v_device_id = ?`, v_device_id);
        if (selectRows.length > 0) {
            if (selectRows[0].tag === ''){
                if (tag !== ''){
                    ctx.body = {
                        result: 201,
                        message: "tag不匹配"
                    };
                    return;
                }
            } else{
                if (tag === '') {
                    ctx.body = {
                        result: 201,
                        message: "tag不匹配"
                    };
                    return;
                }else{
                    json_tag = JSON.parse(selectRows[0].tag.replace(/\'/g,'\"'));
                    json_new_tag = JSON.parse(tag.replace(/\'/g,'\"'));
                    if (json_new_tag.length !== json_tag.length) {
                        ctx.body = {
                            result: 201,
                            message: "tag不匹配"
                        };
                        return;
                    }
                    for (i = 0; i < json_new_tag.length; i++){
                        if (json_tag[i].property_name !== json_new_tag[i].property_name)  {
                            ctx.body = {
                                result: 201,
                                message: "tag不匹配"
                            };
                            return;
                        }
                    }
                }
            }
            selectRows[0].name = name;
            selectRows[0].tag = tag;
            ret = await mysql.query(`UPDATE t_room_v_device SET ? WHERE v_device_id = ?`, [selectRows[0],v_device_id]);
            if (!ret || ret.insertId === -1) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "对象不存在或者已删除"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.getList = async(ctx) => {
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let room_id = ctx.params.room_id || 0;

    if (room_id <= 0){
        ctx.body = {
            result: 201,
            message: "无效的房间id"
        };
        return;
    }
    try {
        let results = await mysql.query(`SELECT * FROM t_room_v_device WHERE room_id = ${room_id} ORDER BY v_device_id LIMIT ${indexfrom}, ${counts} ` );
        let totalResult = await mysql.query(`SELECT COUNT(v_device_id) AS total FROM t_room_v_device WHERE room_id = ${room_id} `);
        ctx.body = {
            result: 200,
            list:results,
            totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
            totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
            message: "查询成功"
        };
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}